<template>
  <div v-if="formJson">
    <el-form
        v-if="formJson.list.length > 0"
        :size="formJson.config.size"
        :label-position="formJson.config.labelPosition"
        :label-width="formJson.config.labelWidth + 'px'"
        ref="formGenerator"
    >
      <div
        v-for="(item, index) in formJson.list"
        :key="index"
        class="formitem-style"
      >
        <el-form-item :label="item.name" :required="item.options.required">
          <form-item-generator :ele-item="item" :ele-config="formJson"></form-item-generator>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
// 表单生成器：接受 data json 数据
import FormItemGenerator from "@/components/FormGenerator/FormItemGenerator";
export default {
  components: {
    FormItemGenerator
  },
  props: {
    formJson: {
      type: Object
    }
  },
  methods: {
    // 表单验证方法
    valueCheck() {
      const promises = [];
      for (const key of this.formJson.list) {
        if (key.options.required) {
          if (key.options.defaultValue instanceof Array) {
            if (key.options.defaultValue.length === 0) {
              if (key.options.requiredMsg) {
                promises.push(Promise.reject(key.options.requiredMsg));
              } else {
                promises.push(Promise.reject(`${key.name}必填`));
              }
            }
          } else {
            if (!key.options.defaultValue) {
              if (key.options.requiredMsg) {
                promises.push(Promise.reject(key.options.requiredMsg));
              } else {
                promises.push(Promise.reject(`${key.name}必填`));
              }
            }
          }
        } else {
          promises.push(Promise.resolve());
        }
      }
      return promises;
    },
    getFormVal() {
      return new Promise((resolve, reject) => {
        Promise.all(this.valueCheck())
            .then((res) => {
              // 读取数据前先清空表单数据
              this.formsVal = {};
              // 循环读取表单数据
              for (const key of this.formJson.list) {
                Object.assign(this.formsVal, {
                  [key.model]: key.options.defaultValue,
                });
              }
              resolve(this.formsVal);
            })
            .catch((err) => {
              this.$message.error(err);
              reject();
            });
      });
    },
  }
}
</script>

<style scoped>

</style>
